package com.yz.controller.excel;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yz.entity.Student;
import com.yz.entity.dto.StudentDto;
import com.yz.service.StudentService;
import com.yz.util.PoiUtils;
import com.yz.util.Result;

@RestController
@RequestMapping("stuexcel")
public class StudentExcelController {

	@Autowired
	StudentService service;
	
	@RequestMapping("/exportStu")
	public void exportStu(HttpServletResponse response, String ids)
			throws IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(new Date());
		String downloadName = "导出的文件"+time+".xls";
		response.setCharacterEncoding("UTF-8");// 设置响应的字符编码格式
		response.setContentType("application/vnd.ms-excel");// 指明响应文件为excel类型
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String(downloadName.getBytes("GB2312"), "ISO8859-1"));// 文件名编码处理，防止浏览器下载文件名乱码
		ServletOutputStream out = response.getOutputStream();
		List<Student> list = new ArrayList<Student>();
		System.out.println("ids" + ids);
		if (ids != null && !ids.equals("")) {
			list = service.queryByIds(ids);
			System.out.println("选中的数据集合=>" + list);
		} else {
			//全查
			list = service.getStu(null);
			System.out.println(list);
		}
		try {
			PoiUtils p = new PoiUtils();
			p.createExcel(list, Student.class, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/uploadStu", name = "导入学生")
	public Object uploadStu(@RequestParam(value = "file") MultipartFile file) {
		String name = file.getName();// form表单中参数名称
		String originalFilename = file.getOriginalFilename();// 得到上传文件的名称
		System.out.println("表单中文件参数名称 name=>" + name);
		System.out.println("上传的文件原始名称 originalfileName=>" + originalFilename);
		PoiUtils poiUtils = new PoiUtils();// Excel工具类
		List<Student> list = null;
		int n = 1;
		try {
			list = (List<Student>) poiUtils.parseExcel(Student.class, file.getInputStream(), originalFilename);
			System.out.println("导入的数据长度：" + list.size());
			for (Student  e: list) {
				 service.addStu(e);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (list!=null) {
			return new Result(0, "上传成功", true);
		} else {
			return new Result(1, "上传失败", false);
		}
	}
}
